<?php

namespace app\models;

use common\domain\components\AccessToken;
use common\models\BkAdmin;
use Yii;
use yii\base\InvalidCallException;
use yii\web\IdentityInterface;

class Admin extends BkAdmin implements IdentityInterface
{

    public function fields(): array
    {
        $fields = parent::fields();

        unset($fields['password']);
        unset($fields['token']);
        unset($fields['token_expire_at']);

        return $fields;
    }

    public function rules(): array
    {
        return [
            [['username'],'required'],
            [['username'],'string','max' => 20],
            [['status',],'integer'],
        ];
    }

    public static function findIdentity($id): ?IdentityInterface
    {
        throw new InvalidCallException();
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        $key = AccessToken::getCacheKey($token);

        // 从cache获取session  （cache有效期600秒 数据库有效期1200秒）
        $user = Yii::$app->cache->get($key);
        if (!$user) {
            $user = BkAdmin::findOne(['token' => $token]);

            if (!$user) {
                return null;
            }

            if ($user->token_expire_at < time()) {
                return null;
            }

            $user->token_expire_at = time() + 1200;
            $user->save();

            // 缓存 sessionID:$userArr   600秒
            Yii::$app->cache->set($key, $user, 600);
        }

        return $user;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey(): string
    {
        throw new InvalidCallException();
    }

    public function validateAuthKey($authKey): bool
    {
        throw new InvalidCallException();
    }
}
